package com.diao.myhub.controller;

import com.alibaba.fastjson.JSON;
import com.diao.myhub.model.dto.ImageDTO;
import com.diao.myhub.exception.CustomizeError;
import com.diao.myhub.exception.CustomizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.diao.myhub.util.FileUtils.uploadToServer;

@Controller
// @PropertySource(factory = YamlPropertySourceFactory.class ,value = "classpath:private.yml")
@Slf4j
public class UploadController {

    @Value("${spring.profiles.active}")
    private String env;
    // 上传文件传输到本地的路径

    @Value("${upload.filepath}")
    private String filepath;

    @RequestMapping("/imgUpload")
    @ResponseBody
    public String imgUpload(@RequestParam("editormd-image-file") MultipartFile file, HttpServletRequest req) {

        String url;
        url = uploadToServer(file, filepath);
        if (url == null) {
            throw new CustomizeException(CustomizeError.FILE_UPLOAD_ERROR);
        }
        ImageDTO imageDTO = new ImageDTO();
        imageDTO.setUrl(url);
        imageDTO.setMessage("ok");
        imageDTO.setSuccess(1);
        return JSON.toJSONString(imageDTO);
    }
}
